<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Blog Posts</title>
</head>
<body>
    <h1>Blog Posts</h1>
    <ul id="post-list"></ul>

    <script>
        // 假设你已经获取了 token，并将其存储在 localStorage 中
        const token = localStorage.getItem('jwt_token'); // 从 localStorage 获取 token

        async function fetchPosts() {
            try {
                const response = await fetch('http://localhost:8000/posts/', {
                    method: 'GET',
                    headers: {
                        'Authorization': `Bearer ${token}`, // 添加 Authorization 头
                        'Content-Type': 'application/json'
                    }
                });

                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }

                const posts = await response.json();
                const postList = document.getElementById('post-list');

                posts.forEach(post => {
                    const listItem = document.createElement('li');
                    listItem.innerHTML = `<h2>${post.title}</h2>
                                          <p>By: ${post.author.name}</p>
                                          <p>${post.content}</p>`; // 修改为 post.content
                    postList.appendChild(listItem);
                });
            } catch (error) {
                console.error('Error fetching posts:', error);
            }
        }

        // Fetch posts when the page loads
        document.addEventListener('DOMContentLoaded', fetchPosts);
    </script>
</body>
</html>
